#include "info_dialog.h"
#include "board_utils.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QFile>
#include <QTextStream>
#include <QApplication>
#include <QLabel>
#include <QTimer>
#include <QProcess>
#include <QComboBox>
#include <QCheckBox>
#include <QStackedWidget>
#include <QMessageBox>

class WifiDialog : public QDialog
{
public:
    WifiDialog(QWidget *parent = nullptr) : QDialog(parent)
    {
        setWindowTitle("WiFi连接设置");
        setModal(true);
        QVBoxLayout *layout = new QVBoxLayout(this);

        QLabel *ssidLabel = new QLabel("选择WiFi：", this);
        ssidCombo = new QComboBox(this);
        QLabel *pwdLabel = new QLabel("密码：", this);
        pwdEdit = new QLineEdit(this);
        pwdEdit->setEchoMode(QLineEdit::Password);
        connectBtn = new QPushButton("连接", this);
        resultLabel = new QLabel(this);

        layout->addWidget(ssidLabel);
        layout->addWidget(ssidCombo);
        layout->addWidget(pwdLabel);
        layout->addWidget(pwdEdit);
        layout->addWidget(connectBtn);
        layout->addWidget(resultLabel);

        QProcess proc;
        proc.start("nmcli -t -f SSID dev wifi");
        proc.waitForFinished();
        QString output = proc.readAllStandardOutput();
        QStringList ssids = output.split('\n', Qt::SkipEmptyParts);
        ssidCombo->addItems(ssids);

        connect(connectBtn, &QPushButton::clicked, this, [=]()
                {
            QString ssid = ssidCombo->currentText();
            QString pwd = pwdEdit->text();
            QProcess connProc;
            QString cmd = QString("nmcli dev wifi connect \"%1\" password \"%2\"").arg(ssid, pwd);
            connProc.start(cmd);
            connProc.waitForFinished();
            QString result = connProc.readAllStandardOutput() + connProc.readAllStandardError();
            resultLabel->setText(result); });
    }

private:
    QComboBox *ssidCombo;
    QLineEdit *pwdEdit;
    QPushButton *connectBtn;
    QLabel *resultLabel;
};

InfoDialog::InfoDialog(QWidget *parent) : QDialog(parent)
{
    setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
    setWindowState(Qt::WindowFullScreen);
    setWindowModality(Qt::ApplicationModal);

    setupUI();
    setupConnections();
    loadConfig();
    brandEdit->setFocus();
    updateClassVariables();
    updateLockButtons();
}

void InfoDialog::setupUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(24);
    mainLayout->setContentsMargins(32, 32, 32, 32);

    // 顶部按钮区
    QWidget *topBtnWidget = new QWidget(this);
    QHBoxLayout *topBtnLayout = new QHBoxLayout(topBtnWidget);
    topBtnLayout->setSpacing(40);
    topBtnLayout->setContentsMargins(0, 0, 0, 0);

    deviceConfigBtn = new QPushButton("设备配置", topBtnWidget);
    offlineOpenBtn = new QPushButton("离线开柜", topBtnWidget);

    QString btnStyle = "QPushButton {"
                       "font-size: 32px;"
                       "font-weight: bold;"
                       "background-color: #01ddfd;"
                       "color: white;"
                       "border-radius: 16px;"
                       "padding: 32px 0px;"
                       "margin: 0px;"
                       "min-height: 80px;"
                       "}"
                       "QPushButton:hover {"
                       "background-color: #0099cc;"
                       "}";

    deviceConfigBtn->setStyleSheet(btnStyle);
    offlineOpenBtn->setStyleSheet(btnStyle);

    topBtnLayout->addWidget(deviceConfigBtn);
    topBtnLayout->addWidget(offlineOpenBtn);
    topBtnWidget->setLayout(topBtnLayout);
    mainLayout->addWidget(topBtnWidget);

    // 下方内容用 QStackedWidget
    stackedWidget = new QStackedWidget(this);

    setupDeviceConfigPage();
    setupOfflinePage();

    stackedWidget->addWidget(deviceConfigWidget); // index 0
    stackedWidget->addWidget(offlineWidget);      // index 1
    mainLayout->addWidget(stackedWidget);

    stackedWidget->setCurrentIndex(0);
}

void InfoDialog::setupDeviceConfigPage()
{
    deviceConfigWidget = new QWidget(this);
    QVBoxLayout *deviceConfigLayout = new QVBoxLayout(deviceConfigWidget);

    QGridLayout *gridLayout = new QGridLayout();

    // 第一行：安科鉴权和外设开关
    authCheck = new QCheckBox("安科鉴权", this);
    cardCheck = new QCheckBox("刷卡", this);
    palmCheck = new QCheckBox("掌静脉", this);
    faceCheck = new QCheckBox("人脸", this);

    authCheck->setStyleSheet("font-size:32px;");
    cardCheck->setStyleSheet("font-size:32px;");
    palmCheck->setStyleSheet("font-size:32px;");
    faceCheck->setStyleSheet("font-size:32px;");

    gridLayout->setHorizontalSpacing(40);
    for (int i = 0; i < 4; ++i)
        gridLayout->setColumnStretch(i, 1);

    gridLayout->addWidget(authCheck, 0, 0);
    gridLayout->addWidget(cardCheck, 0, 1);
    gridLayout->addWidget(palmCheck, 0, 2);
    gridLayout->addWidget(faceCheck, 0, 3);

    // 第二行：品牌代码、门店名称、管理区、SN码、设备类型
    QLabel *brandLabel = new QLabel("品牌代码:", this);
    brandEdit = new QLineEdit(this);
    brandLabel->setStyleSheet("font-size:28px;font-weight:bold;");
    brandEdit->setStyleSheet("font-size:28px;height:56px;");
    brandEdit->setMinimumHeight(56);

    QLabel *storeLabel = new QLabel("门店名称:", this);
    storeEdit = new QLineEdit(this);
    storeLabel->setStyleSheet("font-size:28px;font-weight:bold;");
    storeEdit->setStyleSheet("font-size:28px;height:56px;");
    storeEdit->setMinimumHeight(56);

    QLabel *zoneLabel = new QLabel("管理区:", this);
    zoneEdit = new QLineEdit(this);
    zoneLabel->setStyleSheet("font-size:28px;font-weight:bold;");
    zoneEdit->setStyleSheet("font-size:28px;height:56px;");
    zoneEdit->setMinimumHeight(56);

    QLabel *snLabel = new QLabel("SN码:", this);
    snEdit = new QLineEdit(this);
    snLabel->setStyleSheet("font-size:28px;font-weight:bold;");
    snEdit->setStyleSheet("font-size:28px;height:56px;");
    snEdit->setMinimumHeight(56);

    QLabel *typeLabel = new QLabel("设备类型:", this);
    typeEdit = new QLineEdit(this);
    typeLabel->setStyleSheet("font-size:28px;font-weight:bold;");
    typeEdit->setStyleSheet("font-size:28px;height:56px;");
    typeEdit->setMinimumHeight(56);

    gridLayout->addWidget(brandLabel, 1, 0);
    gridLayout->addWidget(brandEdit, 1, 1);
    gridLayout->addWidget(storeLabel, 1, 2);
    gridLayout->addWidget(storeEdit, 1, 3);
    gridLayout->addWidget(zoneLabel, 1, 4);
    gridLayout->addWidget(zoneEdit, 1, 5);
    gridLayout->addWidget(snLabel, 1, 6);
    gridLayout->addWidget(snEdit, 1, 7);
    gridLayout->addWidget(typeLabel, 1, 8);
    gridLayout->addWidget(typeEdit, 1, 9);

    deviceConfigLayout->addLayout(gridLayout);

    // WiFi设置区
    QGridLayout *wifiLayout = new QGridLayout();
    QLabel *wifiTitle = new QLabel("WiFi配置", this);
    wifiTitle->setStyleSheet("font-size:24px;font-weight:bold;color:#0099cc;");
    wifiLayout->addWidget(wifiTitle, 0, 0, 1, 7);

    QLabel *ssidLabel = new QLabel("选择WiFi：", this);
    QComboBox *ssidCombo = new QComboBox(this);
    QLabel *pwdLabel = new QLabel("密码：", this);
    QLineEdit *pwdEdit = new QLineEdit(this);
    pwdEdit->setEchoMode(QLineEdit::Password);
    QPushButton *connectBtn = new QPushButton("连接", this);
    QLabel *currentWifiLabel = new QLabel("当前连接WiFi：", this);
    QLabel *signalLabel = new QLabel("信号强度：", this);

    wifiLayout->addWidget(ssidLabel, 1, 0);
    wifiLayout->addWidget(ssidCombo, 1, 1);
    wifiLayout->addWidget(pwdLabel, 1, 2);
    wifiLayout->addWidget(pwdEdit, 1, 3);
    wifiLayout->addWidget(connectBtn, 1, 4);
    wifiLayout->addWidget(currentWifiLabel, 1, 5);
    wifiLayout->addWidget(signalLabel, 1, 6);

    QLabel *wifiResultLabel = new QLabel(this);
    QLabel *resultLabel = new QLabel(this);
    QHBoxLayout *resultLayout = new QHBoxLayout();
    resultLayout->addWidget(wifiResultLabel);
    resultLayout->addWidget(resultLabel);
    wifiLayout->addLayout(resultLayout, 2, 0, 1, 7);

    ssidLabel->setStyleSheet("font-size:28px;font-weight:bold;");
    ssidCombo->setStyleSheet("font-size:28px;height:56px;");
    ssidCombo->setMinimumHeight(56);
    pwdLabel->setStyleSheet("font-size:28px;font-weight:bold;");
    pwdEdit->setStyleSheet("font-size:28px;height:56px;");
    pwdEdit->setMinimumHeight(56);
    connectBtn->setStyleSheet("font-size:28px;height:56px;");
    connectBtn->setMinimumHeight(56);
    connectBtn->setMaximumWidth(180);
    currentWifiLabel->setStyleSheet("font-size:28px;font-weight:bold;");
    signalLabel->setStyleSheet("font-size:28px;font-weight:bold;");
    wifiResultLabel->setStyleSheet("font-size:28px;color:#009900;");
    resultLabel->setStyleSheet("font-size:28px;color:#333333;");

    deviceConfigLayout->addLayout(wifiLayout);

    // 操作按钮
    QHBoxLayout *btnLayout = new QHBoxLayout();
    okBtn = new QPushButton("确认", this);
    backBtn = new QPushButton("返回", this);
    updateBtn = new QPushButton("更新", this); // 新增更新按钮
    okBtn->setMinimumHeight(56);
    okBtn->setMaximumWidth(180);
    okBtn->setStyleSheet("font-size:28px;");
    backBtn->setMinimumHeight(56);
    backBtn->setMaximumWidth(180);
    backBtn->setStyleSheet("font-size:28px;");
    updateBtn->setMinimumHeight(56);
    updateBtn->setMaximumWidth(180);
    updateBtn->setStyleSheet("font-size:28px;background:#01ddfd;color:white;");
    btnLayout->addWidget(okBtn);
    btnLayout->addWidget(updateBtn); // 插入到中间
    btnLayout->addWidget(backBtn);
    deviceConfigLayout->addLayout(btnLayout);

    keyboard = KeyboardManager::getInstance().getKeyboard(this);
    keyboard->setFixedHeight(600);
    deviceConfigLayout->addWidget(keyboard);

    QProcess proc;
    proc.start("nmcli -t -f SSID dev wifi");
    proc.waitForFinished();
    QString output = proc.readAllStandardOutput();
    QStringList ssids = output.split('\n', Qt::SkipEmptyParts);
    ssidCombo->addItems(ssids);

    connect(connectBtn, &QPushButton::clicked, this, [=]()
            {
        QString ssid = ssidCombo->currentText();
        QString pwd = pwdEdit->text();
        QProcess connProc;
        QString cmd = QString("nmcli dev wifi connect \"%1\" password \"%2\"").arg(ssid, pwd);
        connProc.start(cmd);
        connProc.waitForFinished();
        QString result = connProc.readAllStandardOutput() + connProc.readAllStandardError();
        wifiResultLabel->setText(result); });

    QTimer *wifiInfoTimer = new QTimer(this);
    connect(wifiInfoTimer, &QTimer::timeout, this, [=]()
            {
        QProcess infoProc;
        infoProc.start("nmcli -t -f ACTIVE,SSID,SIGNAL dev wifi");
        infoProc.waitForFinished();
        QString infoOutput = infoProc.readAllStandardOutput();
        QStringList lines = infoOutput.split('\n', Qt::SkipEmptyParts);
        QString currentSSID;
        QString signal;
        for (const QString &line : lines) {
            QStringList parts = line.split(':');
            if (parts.size() >= 3 && (parts[0] == "是" || parts[0] == "yes")) {
                currentSSID = parts[1];
                signal = parts[2];
                break;
            }
        }
        currentWifiLabel->setText("当前连接WiFi：" + (currentSSID.isEmpty() ? "无" : currentSSID));
        signalLabel->setText("信号强度：" + (signal.isEmpty() ? "无" : signal)); });
    wifiInfoTimer->start(3000);
}

void InfoDialog::setupOfflinePage()
{
    offlineWidget = new QWidget(this);
    QVBoxLayout *offlineLayout = new QVBoxLayout(offlineWidget);

    loadLockBtn = new QPushButton("联网加载柜锁", offlineWidget);
    loadLockBtn->setStyleSheet("font-size:28px;min-height:56px;max-width:240px;");
    offlineLayout->addWidget(loadLockBtn);

    // 新增“开全部锁”按钮
    QPushButton *openAllLocksBtn = new QPushButton("开全部锁", offlineWidget);
    openAllLocksBtn->setStyleSheet("font-size:28px;min-height:56px;max-width:240px;");
    offlineLayout->addWidget(openAllLocksBtn);

    QWidget *lockAreaWidget = new QWidget(offlineWidget);
    lockAreaLayout = new QHBoxLayout(lockAreaWidget);
    lockAreaWidget->setLayout(lockAreaLayout);
    offlineLayout->addWidget(lockAreaWidget);

    offlineWidget->setLayout(offlineLayout);

    // 保存指针以便连接槽函数
    this->openAllLocksBtn = openAllLocksBtn;
}

void InfoDialog::setupConnections()
{
    connect(deviceConfigBtn, &QPushButton::clicked, this, [=]()
            { stackedWidget->setCurrentIndex(0); });
    connect(offlineOpenBtn, &QPushButton::clicked, this, [=]()
            { stackedWidget->setCurrentIndex(1); });

    connect(okBtn, &QPushButton::clicked, this, [=]()
            {
        updateClassVariables();
        QString info = QString(
            "品牌代码: %1\n"
            "门店名称: %2\n"
            "管理区: %3\n"
            "SN码: %4\n"
            "设备类型: %5\n"
            "安科鉴权: %6\n"
            "刷卡: %7\n"
            "掌静脉: %8\n"
            "人脸: %9"
        )
        .arg(m_brandCode)
        .arg(m_storeName)
        .arg(m_zone)
        .arg(m_snCode)
        .arg(m_deviceType)
        .arg(m_authEnabled ? "开启" : "关闭")
        .arg(m_cardEnabled ? "开启" : "关闭")
        .arg(m_palmEnabled ? "开启" : "关闭")
        .arg(m_faceEnabled ? "开启" : "关闭");

        QMessageBox::information(this, "设备信息", info);

        saveConfig();

        // 新增：保存二维码到文件
        BoardUtils::getInstance().httpGetQrCode(m_brandCode.toStdString(), "trial", "qrcode.jpg");

        // 连接到socket服务器
        auto client = BoardUtils::getInstance().socketClient();
        client->close();
        
        // 设置新的 client_id
        client->setClientId((m_brandCode + "_" + m_storeName + "_" + m_zone + "_" + m_snCode).toStdString());
        
        // 再连接
        if (!client->connect("8.152.4.127", 18843, client->getClientId()))
        {
            std::cerr << "首次连接服务器失败，将在后台尝试重连" << std::endl;
            // 继续执行，因为重连会在后台进行
        }
        emit configChanged(); });

    connect(backBtn, &QPushButton::clicked, this, [=]()
            {
        saveConfig();
        QInputMethod *inputMethod = QGuiApplication::inputMethod();
        if (inputMethod) {
            inputMethod->hide();
        }
        QTimer::singleShot(50, this, &InfoDialog::reject); });

    connect(brandEdit, &QLineEdit::textChanged, this, &InfoDialog::updateClassVariables);
    connect(storeEdit, &QLineEdit::textChanged, this, &InfoDialog::updateClassVariables);
    connect(zoneEdit, &QLineEdit::textChanged, this, &InfoDialog::updateClassVariables);
    connect(snEdit, &QLineEdit::textChanged, this, &InfoDialog::updateClassVariables);
    connect(typeEdit, &QLineEdit::textChanged, this, &InfoDialog::updateClassVariables);

    connect(authCheck, &QCheckBox::stateChanged, this, &InfoDialog::updateClassVariables);
    connect(cardCheck, &QCheckBox::stateChanged, this, &InfoDialog::updateClassVariables);
    connect(palmCheck, &QCheckBox::stateChanged, this, &InfoDialog::updateClassVariables);
    connect(faceCheck, &QCheckBox::stateChanged, this, &InfoDialog::updateClassVariables);

    connect(loadLockBtn, &QPushButton::clicked, this, &InfoDialog::onLoadLockBtnClicked);
    connect(openAllLocksBtn, &QPushButton::clicked, this, [this]()
            {
        // 读取所有板号
        QSet<int> boardIds;
        QFile file("lock_list.txt");
        if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            while (!in.atEnd())
            {
                QString line = in.readLine().trimmed();
                QStringList parts = line.split(",");
                if (parts.size() == 3)
                {
                    int controller_id = parts[1].toInt();
                    boardIds.insert(controller_id);
                }
            }
            file.close();
        }

        if (boardIds.isEmpty())
        {
            QMessageBox::warning(this, "提示", "未找到任何板号，无法开全部锁！");
            return;
        }

        int successCount = 0;
        int failCount = 0;
        QString resultMsg;
        for (int boardId : boardIds)
        {
            bool ok = BoardUtils::getInstance().serial()->openAllLocks(boardId);
            if (ok)
            {
                resultMsg += QString("板号 %1 开全部锁成功\n").arg(boardId);
                successCount++;
            }
            else
            {
                resultMsg += QString("板号 %1 开全部锁失败\n").arg(boardId);
                failCount++;
            }
        }
        QMessageBox::information(this, "开全部锁结果", resultMsg); });

        // 连接更新按钮
        connect(updateBtn, &QPushButton::clicked, this, [this]() {
        QProcess *proc = new QProcess(this);
        proc->start("/home/linaro/Desktop/cabinet_board/update.sh");
        if (!proc->waitForStarted(3000)) {
            QMessageBox::warning(this, "更新", "脚本无法启动，请检查权限！");
            return;
        }
        proc->waitForFinished(-1);
        QString output = proc->readAllStandardOutput() + proc->readAllStandardError();
        QMessageBox::information(this, "更新结果", output);
        });
}

void InfoDialog::onLoadLockBtnClicked()
{
    DeviceConfig config = BoardUtils::getInstance().loadDeviceConfig("device_config.txt");
    std::vector<Lock> locks = BoardUtils::getInstance().httpGetAllLocks(
        config.brand_code,
        config.organization,
        config.zone);
    updateLockButtons();
    QMessageBox::information(this, "加载完成", QString("已加载%1个柜锁").arg(locks.size()));
}

void InfoDialog::updateClassVariables()
{
    m_brandCode = brandEdit->text();
    m_storeName = storeEdit->text();
    m_zone = zoneEdit->text();
    m_snCode = snEdit->text();
    m_deviceType = typeEdit->text();
    m_authEnabled = authCheck->isChecked();
    m_cardEnabled = cardCheck->isChecked();
    m_palmEnabled = palmCheck->isChecked();
    m_faceEnabled = faceCheck->isChecked();
}

void InfoDialog::saveConfig()
{
    updateClassVariables();

    // 强制用接口获取auth_enabled
    bool zoneAuthEnabled = BoardUtils::getInstance().httpGetZoneAuthEnabled(
        m_brandCode.toStdString(),
        m_storeName.toStdString(),
        m_zone.toStdString());
    m_authEnabled = zoneAuthEnabled;

    QString content = QString("brand_code=%1\norganization=%2\nzone=%3\nsn_code=%4\ndevice_type=%5\n"
                              "auth_enabled=%6\ncard_enabled=%7\npalm_enabled=%8\nface_enabled=%9")
                          .arg(m_brandCode)
                          .arg(m_storeName)
                          .arg(m_zone)
                          .arg(m_snCode)
                          .arg(m_deviceType)
                          .arg(m_authEnabled ? "1" : "0")
                          .arg(m_cardEnabled ? "1" : "0")
                          .arg(m_palmEnabled ? "1" : "0")
                          .arg(m_faceEnabled ? "1" : "0");

    QFile file("device_config.txt");
    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream out(&file);
        out << content;
        file.close();
    }
}

void InfoDialog::loadConfig()
{
    QFile file("device_config.txt");
    if (file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&file);
        QMap<QString, QString> configMap;
        while (!in.atEnd())
        {
            QString line = in.readLine();
            int separatorPos = line.indexOf('=');
            if (separatorPos > 0)
            {
                QString key = line.left(separatorPos);
                QString value = line.mid(separatorPos + 1);
                configMap[key] = value;
            }
        }
        file.close();

        brandEdit->setText(configMap.value("brand_code"));
        storeEdit->setText(configMap.value("organization"));
        zoneEdit->setText(configMap.value("zone"));
        snEdit->setText(configMap.value("sn_code"));
        typeEdit->setText(configMap.value("device_type"));

        authCheck->setChecked(configMap.value("auth_enabled") == "1");
        cardCheck->setChecked(configMap.value("card_enabled") == "1");
        palmCheck->setChecked(configMap.value("palm_enabled") == "1");
        faceCheck->setChecked(configMap.value("face_enabled") == "1");
        updateClassVariables();
    }
}

void InfoDialog::closeEvent(QCloseEvent *event)
{
    KeyboardManager::getInstance().releaseKeyboard();
    QDialog::closeEvent(event);
}

void InfoDialog::showEvent(QShowEvent *event)
{
    QDialog::showEvent(event);
    if (keyboard && !keyboard->isVisible())
    {
        keyboard->show();
    }
    QTimer::singleShot(100, [this]()
                       { brandEdit->setFocus(); });
}

void InfoDialog::updateLockButtons()
{
    // 清空原有按钮
    QLayoutItem *child;
    while ((child = lockAreaLayout->takeAt(0)) != nullptr) {
        if (child->widget()) child->widget()->deleteLater();
        delete child;
    }
    // 读取txt文件，横向排列，每行6个
    QFile file("lock_list.txt");
    QList<QPushButton*> lockBtns;
    QList<QPair<int,int>> lockInfo; // controller_id, lock_number
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine().trimmed();
            if (!line.isEmpty()) {
                QStringList parts = line.split(",");
                if (parts.size() == 3) {
                    QString cabinet_number = parts[0];
                    int controller_id = parts[1].toInt();
                    int lock_number = parts[2].toInt();
                    QPushButton *lockBtn = new QPushButton(QString("%1号锁").arg(cabinet_number), this);
                    lockBtn->setStyleSheet("font-size:24px;min-width:120px;min-height:36px;");
                    lockBtns.append(lockBtn);
                    lockInfo.append(qMakePair(controller_id, lock_number));
                }
            }
        }
        file.close();
    }
    // 用QGridLayout横向排列
    QGridLayout *grid = new QGridLayout();
    grid->setVerticalSpacing(8); // 设置行间距更小
    for (int i = 0; i < lockBtns.size(); ++i) {
        int row = i / 6;
        int col = i % 6;
        grid->addWidget(lockBtns[i], row, col);
        // 绑定开锁槽
        int controller_id = lockInfo[i].first;
        int lock_number = lockInfo[i].second;
        connect(lockBtns[i], &QPushButton::clicked, this, [controller_id, lock_number, btn=lockBtns[i], this]() {
            bool ok = BoardUtils::getInstance().serial()->openLock(controller_id, lock_number);
            if (ok)
                QMessageBox::information(this, "开锁成功", QString("已打开%1").arg(btn->text()));
            else
                QMessageBox::warning(this, "开锁失败", QString("%1开锁失败").arg(btn->text()));
        });
    }
    QWidget *gridWidget = new QWidget(this);
    gridWidget->setLayout(grid);
    lockAreaLayout->addWidget(gridWidget);
}